package com.y2.authprj.mvc.controller.auth;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;


import com.gdglc.spring.biz.auth.StaffInfoBiz;

import com.y2.authprj.bean.auth.model.StaffInfo;
import com.y2.authprj.bean.auth.vo.ResponeVo;
import com.y2.authprj.exception.BizException;
import com.y2.authprj.utils.CookieUtil;
import com.y2.authprj.utils.UserErrorLoginRecord;



@Controller
@RequestMapping("/auth")
public class TStaffInfoController {
	
	@Resource(name="StaffInfoBiz")
	private StaffInfoBiz staffBiz;

	private static Map<String, UserErrorLoginRecord> LOG_MAP = new HashMap<String, UserErrorLoginRecord>();

	
	
	/***
	 * 登陆验证
	 * @param staffNum 账号
	 * @param pwd 密码
	 * @param model 失败时报告消息
	 * @param model2 成功时储存用户信息
	 * @return
	 */
	@RequestMapping("/login")
	public String login(HttpServletResponse response,HttpServletRequest request,
			String staffNum,String pwd,String rememberPwd,RedirectAttributes model,HttpSession session){
		
		UserErrorLoginRecord userError=null;
		userError = LOG_MAP.get(staffNum);//通过用户名获取登录信息对象
		 //获取时间
		Calendar nowDate = Calendar.getInstance();
        String dateStr = String.valueOf(nowDate.get(Calendar.YEAR)) + (nowDate.get(Calendar.MONTH) + 1) + (nowDate.get(Calendar.DAY_OF_MONTH));
		if(userError!=null ){
			 if(!dateStr.equals(userError.getLoginTime())){
				 LOG_MAP.remove(staffNum);
				 userError=null;
			}
		}
        if(userError==null || userError.getErrorNumber()<3 ){
			try {
				String loginIp=getIpAddr(request);
				StaffInfo staffInfo=staffBiz.checkLogin(staffNum, pwd,loginIp);
				
				session.setAttribute("staffInfo", staffInfo);
				session.setMaxInactiveInterval(600);
				if(null!=rememberPwd){
					addCookie(response, request, staffNum, pwd);
				}else{
					delCookie(response, request, staffNum);
				}
				LOG_MAP.remove(staffNum);
				//跳转到主页面
				return "redirect:/functionauthority/show";
			}catch (BizException e) {
				e.printStackTrace();
				model.addFlashAttribute("message", e.getMessage());
			}catch (Exception e) {
				e.printStackTrace();
				model.addFlashAttribute("message", e.getMessage());
			}
			addMap(userError, staffNum);
		}else{
			model.addFlashAttribute("message", "对不起，您的登陆失败次数太多，系统已经不允许您继续登陆，请联系管理员，或明天在尝试登陆！");
		}
		return "redirect:/auth/showLogin";
	} 
	
	/**
	 * 验证账号是否存在
	 * @param staffNum  账号
	 * @return  存在返回true反之false
	 */
	@RequestMapping("/checkStaffNum")
	@ResponseBody
	public ResponeVo checkStaffNum(HttpServletRequest request,String staffNum){
		ResponeVo vo = new ResponeVo();
		CookieUtil cookieUtil=new CookieUtil();
		Cookie cookie=cookieUtil.getCookieByName(request,staffNum);
		try {
			staffBiz.showByStaffNum(staffNum);
			if(cookie!=null){
				vo.setMessage(cookie.getValue());
			}
		}catch(BizException e){
			vo.setCode(ResponeVo.ERROR);
			vo.setMessage(e.getMessage());
		} catch (Exception e) {
			e.printStackTrace();
			vo.setCode(ResponeVo.ERROR);
			vo.setMessage("执行失败!");
		}
		return vo;
	} 

	
	@RequestMapping("/offLogin")
	public String offLogin(HttpSession session){
		session.removeAttribute("staffInfo");
		return "admin/login";
	} 

	
	@RequestMapping("/showLogin")
	public String shpwLogin(Model model){
		return "admin/login";
	} 
	
	
	
	 /**
      * 获取登录用户IP地址
      * 
      * @param request
      * @return
     */
	 public static String getIpAddr(HttpServletRequest request) {
	     String ip = request.getHeader("x-forwarded-for");
	     if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
	            ip = request.getHeader("Proxy-Client-IP");
	         }
         if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
	             ip = request.getHeader("WL-Proxy-Client-IP");
         }
	     if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
	            ip = request.getRemoteAddr();
	      }
         if (ip.equals("0:0:0:0:0:0:0:1")) {
	            ip = "本地";
         }
	        return ip;
     }
	
	//登陆失败
	public void addMap(UserErrorLoginRecord userError,String account){
		Calendar nowDate = Calendar.getInstance();
		String dateStr = String.valueOf(nowDate.get(Calendar.YEAR)) + (nowDate.get(Calendar.MONTH) + 1) + (nowDate.get(Calendar.DAY_OF_MONTH));
		 if (userError == null) {
             userError = new UserErrorLoginRecord();
             userError.setErrorNumber(1);
             userError.setLoginTime(dateStr);
             LOG_MAP.put(account, userError);
         } else {
             int loginNumber = userError.getErrorNumber();
             userError.setErrorNumber(loginNumber + 1);
             LOG_MAP.put(account, userError);
         }       
	}
	
	//添加cookie
	public void addCookie(HttpServletResponse response,HttpServletRequest request,String name,String value){
			CookieUtil cookieUtil=new CookieUtil();
			Cookie cookie=cookieUtil.getCookieByName(request, name);
			if(null==cookie){
				cookieUtil.addCookie(response, name, value);
			}else{
				cookieUtil.editCookie(request, response, name, value);
			}
	
	} 
	//删除cookie
	public void delCookie(HttpServletResponse response,HttpServletRequest request,String name){
		CookieUtil cookieUtil=new CookieUtil();
		cookieUtil.delCookie(request, response, name);
	} 

}
